package org.lanqiao.service.impl;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.lanqiao.information.Answer;
import org.lanqiao.information.IAnswerService;
import org.lanqiao.mapper.AnswerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service(interfaceClass = IAnswerService.class, timeout = 5000)
public class AnswerServiceImpl implements IAnswerService {

    @Autowired
    AnswerMapper answerMapper;

    @Override
    public IPage<Answer> pageListByUserId(Integer pageNum, Integer pageSize, Map<String, String> queryMap) {
        IPage<Answer> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Answer> queryWrapper = queryWrapper1(queryMap);
        // 获取分页数据
        IPage<Answer> answerIPage = answerMapper.selectPage(page, queryWrapper);
        // 我们遍历分页数据
        for (Answer record : answerIPage.getRecords()) {
            // 如果回答数据里面没有内容 则将其变为空字符串
            if (record.getLikedIds() == null) {
                record.setLikedIds("");
            }
            // 如果回答数据里面存在当前用户userId 说明当前用户已经给这条回答点过赞
            if (Arrays.asList(record.getLikedIds().split(", ")).contains(queryMap.get("userId") + "")) {
                record.setIsLike(1);
            } else {
                record.setIsLike(0);
            }
        }
        return answerIPage;
    }

    @Override
    @Transactional
    public void add(Answer answer) {
        answerMapper.insert(answer);
    }

    @Override
    public void logicallyDelete(Integer ansId) {
        Answer answer = new Answer();
        answer.setAnsId(ansId);
        answer.setStatus(4);
        answerMapper.updateById(answer);
    }

    @Override
    @Transactional
    public void physicallyDelete(Integer ansId) {
        answerMapper.deleteById(ansId);
    }

    @Override
    public void update(Answer answer) {
        answerMapper.updateById(answer);
    }

    @Override
    public List<Answer> findAll() {
        List<Answer> answers = answerMapper.selectList(null);
        return answers;
    }

    @Override
    public List<Answer> findAll(Integer userId) {
        // 判断点赞列表中是否有这个用户id
        List<Answer> answers = answerMapper.selectList(null);
        for (Answer answer : answers) {
            if (Arrays.asList(answer.getLikedIds().split(", ")).contains(userId + "")) {
                answer.setIsLike(1);
            } else {
                answer.setIsLike(0);
            }
        }
        return answers;
    }

    @Override
    public List<Answer> findList(Map map) {
        QueryWrapper<Answer> queryWrapper = queryWrapper(map);
        List<Answer> answerList = answerMapper.selectList(queryWrapper);
        if (map.get("userId") != null) {
            Integer userId = Integer.valueOf(String.valueOf(map.get("userId")));
            for (Answer answer : answerList) {
                if (Arrays.asList(answer.getLikedIds().split(", ")).contains(userId + "")) {
                    answer.setIsLike(1);
                } else {
                    answer.setIsLike(0);
                }
            }
        }
        return answerList;
    }

    @Override
    public IPage<Answer> pageAll(Integer pageNum, Integer pageSize) {
        IPage<Answer> page = new Page<>(pageNum, pageSize);
        IPage<Answer> answerIPage = answerMapper.selectPage(page, null);
        return answerIPage;
    }


    @Override
    public IPage<Answer> pageAll(Integer pageNum, Integer pageSize, Integer userId) {
        IPage<Answer> page = new Page<>(pageNum, pageSize);
        IPage<Answer> answerIPage = answerMapper.selectPage(page, null);
        List<Answer> answerList = answerIPage.getRecords();
        for (Answer answer : answerList) {
            if (Arrays.asList(answer.getLikedIds().split(", ")).contains(userId + "")) {
                answer.setIsLike(1);
            } else {
                answer.setIsLike(0);
            }
        }
        return answerIPage;
    }


    @Override
    public IPage<Answer> pageList(Integer pageNum, Integer pageSize, Map<String, String> queryMap) {
        IPage<Answer> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Answer> queryWrapper = queryWrapper(queryMap);
        // 获取分页数据
        IPage<Answer> answerIPage = answerMapper.selectPage(page, queryWrapper);

        // 我们获取用户的id 用来查找 用户是否已经点赞过某个回答
        if (queryMap.get("userId") != null) {
            // 获取用户userId
            Integer userId = Integer.valueOf(String.valueOf(queryMap.get("userId")));
//            queryWrapper.eq("user_id", userId);
            // 获取分页数据
            answerIPage = answerMapper.selectPage(page, queryWrapper);
            // 我们遍历分页数据
            for (Answer record : answerIPage.getRecords()) {
                // 如果回答数据里面没有内容 则将其变为空字符串
                if (record.getLikedIds() == null) {
                    record.setLikedIds("");
                }
                // 如果回答数据里面存在当前用户userId 说明当前用户已经给这条回答点过赞
                if (Arrays.asList(record.getLikedIds().split(", ")).contains(userId + "")) {
                    record.setIsLike(1);
                } else {
                    record.setIsLike(0);
                }
            }
        }
        return answerIPage;
    }

    @Override
    public void inform(Map informMap) {
        Integer ansId = Integer.parseInt(String.valueOf(informMap.get("ansId")));
        Integer informUserId = Integer.parseInt(String.valueOf(informMap.get("informUserId")));
        String informContent = (String) informMap.get("informContent");
        if (ansId == null || informContent == null || informUserId == null) {
            throw new RuntimeException("缺少举报条件");
        }
        Answer answer = new Answer();
        answer.setAnsId(ansId);
        answer.setInformUserId(informUserId);
        answer.setInformContent(informContent);
        answer.setStatus(3);

        answerMapper.updateById(answer);
    }


    @Override
    public void informSuccess(Integer ansId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("ans_id", ansId);
        Answer answer = new Answer();
        answer.setAnsId(ansId);
        answer.setStatus(4);
        answerMapper.updateById(answer);
    }

    @Override
    public void informFail(Integer ansId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("ans_id", ansId);
        Answer answer = new Answer();
        answer.setAnsId(ansId);
        answer.setInformContent("");
        answer.setInformUserId(null);
        answer.setStatus(1);
        answerMapper.updateById(answer);
    }

    /**
     * 点赞功能
     * @param map
     */
    @Override
    public void toggleLike(Map map) {
        // 获取回答answerId
        Integer answerId = Integer.parseInt(String.valueOf(map.get("answerId")));
        // 获取用户userId
        Integer userId = Integer.parseInt(String.valueOf(map.get("userId")));
        // 我们有了answerId 就可以查找唯一的回答实体
        Answer answer = answerMapper.selectById(answerId);
        // 获取回答实体的点赞人集合
        List<String> list = null;
        if (answer.getLikedIds() == null || answer.getLikedIds().equals("")) {
            answer.setLikedIds("");
            list = Arrays.asList(answer.getLikedIds());
        } else {
            System.out.println("b");
            list = Arrays.asList(answer.getLikedIds().split(", "));
        }
        list = new ArrayList<String>(list);
        // 判断当前用户userId是否在点赞列表中
        if (list.contains(userId + "")) {
            // 如果包含 则将其删除
            list.remove(userId + "");
            // 减少一个赞
            answer.setLikedCount(answer.getLikedCount() - 1);
        } else {
            // 如果不包含 则增加
            list.add(userId + "");
            // 增加一个赞
            answer.setLikedCount(answer.getLikedCount() + 1);
        }
        // 去除所有空字符串
        list = list.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
        String[] tempArr = new String[list.size()];
        // 将集合转换为数组
        String[] array = list.toArray(tempArr);
        // 使用工具类将数组转换为字符串
        String ids = StringUtils.join(array, ", ");

        Answer ans = new Answer();
        ans.setAnsId(answerId);
        ans.setLikedIds(ids);
        ans.setLikedCount(answer.getLikedCount());
        // 更新回答answer实体
        answerMapper.updateById(ans);
    }

    private QueryWrapper<Answer> queryWrapper(Map<String, String> queryMap){
        // 查询条件
        QueryWrapper<Answer> queryWrapper = null;
        if(queryMap !=null){
            queryWrapper = new QueryWrapper<>();
            if(!StringUtils.isEmpty(queryMap.get("ansId"))){
                queryWrapper.eq("ans_id",queryMap.get("ansId"));
            }
            if(!StringUtils.isEmpty(queryMap.get("content"))){
                queryWrapper.like("content",queryMap.get("content"));
            }
            if(!StringUtils.isEmpty(queryMap.get("status"))){
                queryWrapper.eq("status",queryMap.get("status"));
            }
            if(!StringUtils.isEmpty(queryMap.get("informUserId"))){
                queryWrapper.eq("inform_user_id",queryMap.get("informUserId"));
            }
            if(!StringUtils.isEmpty(queryMap.get("informContent"))){
                queryWrapper.like("inform_content",queryMap.get("informContent"));
            }
            if(!StringUtils.isEmpty(queryMap.get("askId"))){
                queryWrapper.like("ask_id",queryMap.get("askId"));
            }
//            if(!StringUtils.isEmpty(queryMap.get("userId"))){
//                queryWrapper.like("user_id",queryMap.get("userId"));
//            }
            if(!StringUtils.isEmpty(queryMap.get("orderby"))){
                queryWrapper.orderByDesc(new String[] {(String) queryMap.get("orderby")});
            }
        }
        return  queryWrapper;
    }

    private QueryWrapper<Answer> queryWrapper1(Map<String, String> queryMap){
        // 查询条件
        QueryWrapper<Answer> queryWrapper = null;
        if(queryMap !=null){
            queryWrapper = new QueryWrapper<>();
            if(!StringUtils.isEmpty(queryMap.get("ansId"))){
                queryWrapper.eq("ans_id",queryMap.get("ansId"));
            }
            if(!StringUtils.isEmpty(queryMap.get("content"))){
                queryWrapper.like("content",queryMap.get("content"));
            }
            if(!StringUtils.isEmpty(queryMap.get("status"))){
                queryWrapper.eq("status",queryMap.get("status"));
            }
            if(!StringUtils.isEmpty(queryMap.get("informUserId"))){
                queryWrapper.eq("inform_user_id",queryMap.get("informUserId"));
            }
            if(!StringUtils.isEmpty(queryMap.get("informContent"))){
                queryWrapper.like("inform_content",queryMap.get("informContent"));
            }
            if(!StringUtils.isEmpty(queryMap.get("askId"))){
                queryWrapper.like("ask_id",queryMap.get("askId"));
            }
            if(!StringUtils.isEmpty(queryMap.get("userId"))){
                queryWrapper.eq("user_id",queryMap.get("userId"));
            }
            if(!StringUtils.isEmpty(queryMap.get("orderby"))){
                queryWrapper.orderByDesc(new String[] {(String) queryMap.get("orderby")});
            }
        }
        return  queryWrapper;
    }
}
